package com.v512.guestbook;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetMessageServlet extends HttpServlet {

	private static final long serialVersionUID = 6773567775114745153L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String driver = "org.gjt.mm.mysql.Driver";
		String url = "jdbc:mysql://127.0.0.1:3306/usermanager";
		String username = "root";
		String password = "123456";
		String sql = "select * from guestbook order by id desc";// 插入数据
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head><title>display messages</title></head>");
		out.println("<body>");
		out.println("<a href='/guestbook/addMessage.html'>添加留言</a><br><br>");
		out.println("留言内容<br><br>");
		try {
			Class.forName(driver);
			Connection conn = DriverManager.getConnection(url, username, password);
			PreparedStatement ps = conn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				printRow(out, rs);
			}
			out.println("</body>");
			out.println("</html>");
			rs.close();
			ps.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void printRow(PrintWriter out, ResultSet rs) throws SQLException {
		out.println("<table width='600' border='1'>");
		out.println("<tr><td width='90'>留言编号</td>");
		out.println("<td width='550'>" + rs.getInt("id") + "</td></tr>");
		out.println("<tr><td width='90'>留言人姓名</td>");
		out.println("<td width='550'>" + rs.getString("name") + "</td></tr>");
		out.println("<tr><td width='90'>留言人电话</td>");
		out.println("<td width='550'>" + StringUtil.chanageNull(rs.getString("phone"), "未写") + "</td></tr>");
		out.println("<tr><td width='90'>留言主题</td>");
		out.println("<td width='550'>" + rs.getString("title") + "</td></tr>");
		out.println("<tr><td width='90'>留言内容</td>");
		out.println("<td width='550'>" + rs.getString("content") + "</td></tr>");
		out.println("<tr><td width='90'>留言时间</td>");
		out.println("<td width='550'>" + rs.getString("time") + "</td></tr>");
		out.println("</table>");
		out.println("<br>");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
